/*
这是一个微信授权的类，需要的参数是
必须参数：appid，redirect_uri，secret
不必要参数：response_type（ 返回类型，请填写code）,state（重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节；）
成员属性：refresh_token；
成员方法：getCode获取code,参数可以不填;
getUserInfo
*/
function OAuth(appid,redirect_uri,secret,response_type,state,app){
  //OAuth的成员
  this.appid = appid;
  this.redirect_uri = encodeURIComponent(redirect_uri);
  this.secret = secret;
  this.response_type = response_type||"code";
  this.state = state || "STATE";
  this.refresh_token;
  this.app = app;
  this.url;
}
OAuth.prototype.getCode = function(req,res,url){
  this.url = url;
  res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?'+'appid='+this.appid+'&redirect_uri='+this.redirect_uri+'&response_type='+this.response_type+'&scope=snsapi_userinfo&state='+this.state+'#wechat_redirect');
}
OAuth.prototype.getUserInfo = function(code,req,res,testurl){
      AV.Cloud.httpRequest({
            url: 'https://api.weixin.qq.com/sns/oauth2/access_token?'+'appid='+this.appid+'&secret='+this.secret+'&code='+code+'&grant_type=authorization_code', 
            success: function (httpResponse) {
               // res.send(httpResponse.text);
               var result = JSON.parse(httpResponse.text);
               var token = result.access_token;
               var openId = result.openid;
               this.refresh_token = result.refresh_token;

               //set user
                    AV.User._logInWith("weixin", {
                       "authData": JSON.parse(httpResponse.text),
                        success: function(user){
                            //返回绑定后的用户
                            // res.send(user);
                            console.dir(user);
                        },
                        error: function(err){
                           console.dir(err);
                        }
                    });
                    res.send(AV.User.current());
                    //   var user = AV.User;
                    //   user._linkWith("weixin", {
                    //    "authData": JSON.parse(httpResponse.text),
                    //     success: function(user){
                    //         //返回绑定后的用户
                    //         // res.send(user);
                    //         console.dir(user);
                    //     },
                    //     error: function(err){
                    //        console.dir(err);
                    //     }
                    // })

                    res.render(testurl);

              //   AV.Cloud.httpRequest({
              //     url: 'https://api.weixin.qq.com/sns/userinfo?access_token='+token+'&openid='+openId+'&lang=zh_CN', 
              //     success: function (httpResponse) {
              //       // this.app.set('test',JSON.parse(httpResponse.text));
              //       var userInfo = JSON.parse(httpResponse.text);
              //        // res.send(JSON.parse(httpResponse.text));
              //        var openid = userInfo.openid;

                     

              //     },
              //     error: function (httpResponse) {
              //         renderError(res, 'Search error.' + searchcontent);
              //         //console.error('Request failed with response code ' + httpResponse.status);
              //     }
              // });
            },
            error: function (httpResponse) {
                renderError(res, 'Search error.' + searchcontent);
                //console.error('Request failed with response code ' + httpResponse.status);
            }
        });
}
OAuth.prototype.getOpenIdCode = function(){
  res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?'+'appid='+this.appid+'&redirect_uri='+this.redirect_uri+'&response_type='+this.response_type+'&scope=snsapi_base&state='+this.state+'#wechat_redirect');
}
OAuth.prototype.refreshToken = function(){
  AV.Cloud.httpRequest({
            url: 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='+this.appid+'&grant_type=refresh_token&refresh_token='+this.refresh_token, 
            success: function (httpResponse) {
               res.send(httpResponse.text);
                //console.log(httpResponse.text);
            },
            error: function (httpResponse) {
                renderError(res, 'Search error.' + searchcontent);
                //console.error('Request failed with response code ' + httpResponse.status);
            }
        });
}

exports.OAuth = OAuth;